package org.huang.sample10.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.huang.sample10.config.support.MybatisConfigurationSupport;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

/**
 * @描述：DB1Config类描述
 * @作者: huanganwei
 * @创建时间: 2021-07-31 00:43:36
 * @版本: 1.0
 */
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = "org.huang.sample10.dal.dao.db2",
        sqlSessionFactoryRef = "db2SqlSessionFactory",
        sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class DB2Config {


    @Bean("db2MybatisProperties")
    @ConfigurationProperties(prefix = "mybatis.db2") //读取application.yml中的配置参数映射成为一个对象
    public MybatisProperties db2MybatisProperties(){
        return new MybatisProperties();
    }


    @Bean("db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2") //读取application.yml中的配置参数映射成为一个对象
    public DataSource db2DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("db2SqlSessionFactory")
    public SqlSessionFactory db2SqlSessionFactory() throws Exception {
        return MybatisConfigurationSupport.sqlSessionFactoryOf(db2MybatisProperties(),db2DataSource());
    }

    @Bean("db2SqlSessionTemplate")
    public SqlSessionTemplate db2SqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(db2SqlSessionFactory());
    }


    @Bean("db2TransactionManager")
    public PlatformTransactionManager db2TransactionManager() {
        return new DataSourceTransactionManager(db2DataSource());
    }

    @Bean("db2TransactionTemplate")
    public TransactionTemplate db2TransactionTemplate(){
        return new TransactionTemplate(db2TransactionManager());
    }
}
